<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\web\JsExpression;
use backend\assets\PrintAsset;
PrintAsset::register($this);
/* @var $this yii\web\View */
/* @var $model common\models\business\BusinessSaleorder */
/* @var $form yii\widgets\ActiveForm */
$ctotal =0;
$selltotal = 0;
?>

<div class="row">
    <div class="col-lg-12">
        <section class="panel">
        <div class="panel-body">
            <?php $form = ActiveForm::begin([
                'options' => ['class' => 'form-horizontal','enctype' => 'multipart/form-data'],
                'fieldConfig' => [
                    'template' => "<div class='col-xs-3 col-sm-2 text-right'>{label}</div><div class='col-xs-9 col-sm-7'>{input}</div><div class='col-xs-12 col-xs-offset-3 col-sm-3 col-sm-offset-0'>{error}</div>",
                ]
            ]); ?>
            <div class="adv-table editable-table ">
                <div class="business-saleorder-form">


                    <?= $form->field($model, 'ordersn')->textInput(['maxlength' => true,'readonly'=>true,'value'=>date('YmdHis').rand(10000,99999)]) ?>


                    <?= $form->field($model, 'customerid')->widget(\kartik\select2\Select2::className(), [
                        'options' => ['placeholder' => '请输入大客户名称 ...'],
                        'initValueText'=>!$model->customer?'':$model->customer->name,
                        'pluginOptions' => [
                            'allowClear' => true,
                            'minimumInputLength' => 1,//重要
                            'language' => [
                                'errorLoading' => new JsExpression("function () { return 'Waiting...'; }"),
                            ],
                            'ajax' => [
                                'url' => '/business/search/search-customer',
                                'dataType' => 'json',
                                'data' => new JsExpression('function(params) { return {q:params.term}; }'),
                                'cache' => true
                            ],
                            'width' => '400px',
                            'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
                            'templateResult' => new JsExpression('function(res) { return res.text; }'),
                            'templateSelection' => new JsExpression('function (res) { return res.text; }'),
                        ],
                    ]);
                    ?>

                    <?= $form->field($model, 'senddate')->textInput(['maxlength' => true,'disabled'=>true]) ?>

                    <?= $form->field($model, 'paytime')->textInput(['maxlength' => true,'disabled'=>true]) ?>

                    <?= $form->field($model, 'price')->textInput(['maxlength' => true,'type'=>'number','disabled'=>true]) ?>
                    <?= $form->field($model, 'status')->dropDownList(\common\models\business\BusinessSaleorder::$statues) ?>

                    <?= $form->field($model, 'ispre_sale')->dropDownList(\common\models\business\BusinessSaleorder::$ispre) ?>
                    <?= $form->field($model, 'remark')->textarea() ?>

                </div>
            </div>

                    <div class="row">
                        <div class="col-md-10 col-md-offset-1">
                            <table class="table table-striped" id="cost">
                                <tr>
                                    <th style="width: 10%">生猪编号</th>
                                    <th style="width: 10%">毛重</th>
                                    <th style="width: 10%">参考成本</th>
                                    <th style="width: 10%">售价 <span id="jisuan" class="btn-default btn btn-xs">计算合计</span> </th>
                                    <th style="width: 20%">备注</th>
                                    <th style="width: 10%">操作</th>
                                </tr>
                                <?php foreach ($model->pigSaleDetail as $item => $value)  { ?>
                                    <?php $selltotal += $value['price'] ?>
                                    <?php $ctotal += $value->pig->getTotal() ?>

                                    <tr class="costdata">
                                        <input type="hidden" name="id[]" value="<?= $value['id'] ?>" disabled="true">
                                        <td>
                                            <input type="text" class="form-control" value="<?= $value['no'] ?>" name="no[]" disabled="true">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control" value="<?= $value['weight'] ?>" name="weight[]" disabled="true">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control" value="<?= $value->pig->getTotal() ?>" disabled="true">
                                        </td>
                                        <td>
                                            <input type="number" class="form-control pprice" value="<?= $value['price'] ?>" name="price[]" disabled="true">
                                        </td>
                                        <td><input type="text" class="form-control" value="<?= $value['remark'] ?>" name="remark[]" disabled="true"></td>
                                    </tr>

                                <?php } ?>

                                <tr class="costdata" id="zongji">
                                    <td><b>总计</b></td>
                                    <td></td>
                                    <td><b id="ctotal"><?= $ctotal ?></b></td>
                                    <td><b id="ptotal"><?= $selltotal ?></b></td>
                                    <td></td>
                                </tr>
                            </table>

                            <div class="form-group">
                                <?= Html::button('添加一项明细',['id'=>'ccopy','class'=>'btn btn-info']) ?>
                                <?= Html::submitButton($model->isNewRecord ? '确认提交' : '确认更新', ['class' => $model->isNewRecord ? 'btn btn-success sub' : 'btn btn-primary sub']) ?>
                            </div>

                        </div>
                    </div>
                    <?php ActiveForm::end(); ?>
        </div>
    </section>
</div>
</div>




<!--选择库存模态窗-->
<div class="modal fade" id="kucun" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="kucuntitle">现有库存</h4>
            </div>
            <div class="modal-body">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="savekucun">保存</button>
            </div>
        </div>
    </div>
</div>




<script>
    <?php $this->beginBlock('js_end') ?>

    $(document).ready(function() {

        //库存的选择的数据，防止前端多次选择库存相同的产品
        var selkudata = [];

        //添加一项
        $('#ccopy').on('click',function (){

            //是否整猪预售
            var ispre = $('#businesssaleorder-ispre_sale').val();
            $.post('/business/sale-pigorder/search-kucun',{selid:selkudata,ispre:ispre},function(html){
                $('#kucun .modal-body').html(html);
                $('#kucun').modal({
                    keyboard: false
                })
            })

        });

        //删除一项
        $('#cost').on('click','.del',function () {
            if (confirm('确定要删除吗？')) {
                $(this).parent().parent().parent('.costdata').remove();
            }
        });


        //保存选择的库存
        $('#savekucun').click(function(){
            var data = $('#kucunsel').val();
            if(data === null){
                //没有选关闭窗口
                $('#kucun').modal('hide');
                return false;
            }
            //合并此页面已经选择的猪，为了防止重复添加
            selkudata = selkudata.concat(data);
            //选择了，去请求
            var ispre = $('#businesssaleorder-ispre_sale').val();
            $.post('/business/sale-pigorder/getkuinfo',{data:data,ispre:ispre},function(html){
                var str = '';
                $(html).each(function(idnex,res){
                    str += '<tr class="costdata"> <input type="hidden" name="id[]" value="'+res.id+'"> <td> <input type="text" class="form-control" value="'+res.no+'" name="no[]" readonly="true"> </td> <td> <input type="text" class="form-control" value="'+res.grossweight+'" name="weight[]" readonly="true"> </td> <td> <input type="number" class="form-control" value="'+res.totalcost+'" readonly="true"> </td> <td> <input type="number" class="form-control pprice" value="'+res.price+'" name="price[]"> </td> <td><input type="text" class="form-control" value="" name="remark[]"></td> <td> <div style="float: left;width: 13%;margin-left: 1%"> <?= Html::button('删除此项',['class'=>'btn btn-warning btn-sm del']) ?> </div> </td> </tr>';
                });

                $('#kucun').modal('hide');
                $('.costdata').last().before(str);
            },'json');
        });


        //点击计算合计
        $("#jisuan").on('click',function(){
            var total = 0;
            $('.pprice').each(function(index,v){
                total += parseFloat($(this).val());
            })
            console.log(total);
            $('#ptotal').text(total.toFixed(2));
        });

        //预售和现卖不能混在一起
        var tmp_sel = $('#businesssaleorder-ispre_sale').val();
        $('#businesssaleorder-ispre_sale').change(function(){
            //更新的时候，是什么单不能切换
            <?php if(!$model->isNewRecord) {?>
                $('#businesssaleorder-ispre_sale').val(tmp_sel);
                return false;
            <?php } ?>

            if(selkudata.length != 0){
                if(confirm('整猪预售单和售卖出栏的销售单，只能选择一种，您确定切换？')){
                    window.location.reload();
                }
                $('#businesssaleorder-ispre_sale').val(tmp_sel);
                return false;
            }
        })



    });
    <?php $this->endBlock(); ?>
    <?php $this->registerJs($this->blocks['js_end'],\yii\web\View::POS_END);//将编写的js代码注册到页面底部 ?>
</script>
